<template>
  <!-- 添加或修改项目基础信息管理对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="100%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <el-card class="box-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="产品编码" prop="code">
          <el-input v-model="queryParams.code" placeholder="请输入产品编码" style="width: 150px;" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入产品名称" style="width: 150px;" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="产品型号" prop="model">
          <el-input v-model="queryParams.model" placeholder="请输入产品型号" style="width: 150px;" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="submitTodo">添 加</el-button>
        </el-form-item>
      </el-form>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-table border v-loading="loading" :data="columns" @selection-change="handleSelectionChange" ref="table"
          :max-height="400" @sort-change="handleSortChange" show-summary :summary-method="getSummaries">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column sortable label="产品编码" align="center" prop="code" />
          <el-table-column sortable label="产品名称" align="center" prop="name" show-overflow-tooltip />
          <el-table-column sortable label="产品型号" align="center" prop="model" />
          <el-table-column sortable label="工程名称" align="center" prop="gongchengName">
            <template slot-scope="scope">
              <el-input v-model="scope.row.gongchengName" size="mini"></el-input>
            </template>
          </el-table-column>
          <el-table-column sortable label="订单编号" align="center" prop="projectNo">
            <template slot-scope="scope">
              <el-input v-model="scope.row.projectNo"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="需求日期" align="center" prop="saleDate">
            <template slot-scope="scope">
              <el-date-picker clearable style="width: 130px" size="mini" v-model="scope.row.saleDate" type="date"
                value-format="yyyy-MM-dd" placeholder="需求日期">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="自制数量" align="center" prop="counts">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.counts" size="mini"></el-input-number>
            </template>
          </el-table-column>
          <!-- <el-table-column label="生产完成" align="center" prop="finishdoCount" />
            <el-table-column label="入库数量" align="center" prop="rukuCount" />-->
          <!--            <el-table-column label="销售总价（不含税）" align="center" prop="goodsTotalPrice"/>-->
          <!--            <el-table-column label="销售总价（含税）" align="center" prop="goodsTaxTotalPrice"/>-->
          <el-table-column label="备注">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" size="mini"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </el-card>

    <div>
      <el-date-picker clearable placeholder="请选择需求日期" type="date" v-model="form.saleDate" value-format="yyyy-MM-dd"
        style="width: 18%;">
      </el-date-picker>
      <el-date-picker clearable placeholder="请选择计划开始时间" type="date" v-model="form.planStartDate"
        value-format="yyyy-MM-dd" style="width: 18%;margin-left:1%">
      </el-date-picker>
      <el-date-picker clearable placeholder="请选择计划结束时间" type="date" v-model="form.planFinishDate"
        value-format="yyyy-MM-dd" style="width: 18%;margin-left:1%">
      </el-date-picker>
      <el-input v-model="form.workshopName" placeholder="生产车间" style="width: 25%;margin-left:1%" />
    </div>

    <el-card class="box-card">
      <el-table :data="columns2" ref="dragTable" row-key="id" v-loading="loading2" show-summary
        :summary-method="getSummaries" max-height="700">
        <el-table-column align="center" label="序号" type="index" width="50">
          <template slot-scope="scope">
            <span>{{ (queryParams2.pageNum - 1) * queryParams2.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <!--   <el-table-column label="生产订单号" align="center" prop="produceNo"/>-->
        <el-table-column sortable label="产品编码" align="center" prop="code" />
        <el-table-column sortable label="产品名称" align="center" prop="name" show-overflow-tooltip />
        <el-table-column label="订单编号" align="center" prop="projectNo" />
        <el-table-column sortable label="工程名称" align="center" prop="gongchengName" />
        <el-table-column sortable label="产品型号" align="center" prop="xinghao" />
        <el-table-column label="自制数量" align="center" prop="count" />
        <el-table-column sortable label="需求日期" align="center" prop="saleDate" width="120">
          <template slot-scope="scope">
            <!-- <span>{{ parseTime(scope.row.saleDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>-->
            <span>{{ parseTime(scope.row.saleDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="150" align="center" prop="remark" show-overflow-tooltip />
        <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
          <template slot-scope="scope">
            <el-popconfirm :title="`确认删除 ` + scope.row.name + ` 数据项？`" @confirm="handleDelete(scope.row)"
              style="margin-left: 10px;">
              <el-button icon="el-icon-delete" size="mini" slot="reference" type="text">删除
              </el-button>
            </el-popconfirm>
            <!--<el-button style="margin-left: 20px;" v-if="scope.row.status==='0'" size="mini" type="text"
                       icon="el-icon-edit" @click="editGoods(scope.row)">编辑
            </el-button>-->
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitProd" v-if="">生成库存生产单</el-button>
      <el-button @click="cancel">暂存订单</el-button>
    </div>
    <edit-goods-form @ok="getList2" ref="editGoodsForm"></edit-goods-form>
  </el-dialog>
</template>

<script>
import { accAdd, accMul, accDiv, addAction, deleteAction, getAction, getById, updateAction } from '@/api/manage'
import EditGoodsForm from '@/views/develop/projectBaseInfo/module/EditGoodsForm.vue'; // 引入 EditGoodsForm 组件
import { listQinggou } from "@/api/develop/goodsSaledo";

export default {
  name: "KucunShengchanProdForm",
  dicts: ['goods_customer', 'company', 'yes_no', 'buy_type', 'goods_type'],
  components: {
    EditGoodsForm // 注册 EditGoodsForm 组件
  },
  data() {
    return {
      // 遮罩层
      title: "生产订单",
      loading: false,
      open: false,
      // 选中数组
      ids: [],
      proId: "",
      proStatus: "",
      saleType: "2",
      goodsType: "",
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库信息管理表格数据
      dataList: [],
      columns: [],
      dateRange: [],
      rules: {},
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        type: null,
        goodsId: null,
        goodsName: null,
        goodsBrand: null,
        goodModel: null,
        goodsUnitPrice: null,
        goodsCount: null,
        goodsTotalPrice: null,
        goodsBuyPrice: null,
        goodsBuyTotal: null,
        goodsProfit: null,
        saleDate: null,
        supplierId: null,
        supplierName: null,
        customerId: null,
        customerName: null,
        invoice: null,
        invoiceId: null,
        invoiceNo: null,
        fundCallback: null,
        receipt: null,
        saleId: null,
        saleName: null,
        projectId: null,
        projectNo: null,
        projectName: null,
        gongchengName: null,
        status: null,
        deptId: null,
        deptName: null,
        counts: null,
        shengyu: null,
        isfahuo: null,
        fahuoDate: null,
        huikuanDate: null,
        goodsCode: null,
        dun: null,
        nos: null,
        isdo: "1",
        mainId: null,
        prodstatus: "0"
      },
      queryParams2: {
        pageNum: 1,
        pageSize: 10000,
        status: "0",
        produceId: null,
        saleId: null,
        caigouId: null,
        count: null,
        code: null,
        name: null,
        xinghao: null,
        miaoshu: null,
        /*orderByColumn: "idx",
        isAsc: "asc"*/
      },
      total2: '',
      loading2: '',
      columns2: [],
      url: {
        list: '/goodsOrderIn/goodsOrderIn/list',
        remove: '/goodsOrderIn/goodsOrderIn/',
        export: '/goodsOrderIn/goodsOrderIn/export',
        insertTodoOther: '/factoryProduceSaleAll/factoryProduceSaleAll/insertTodoOther',
        list2: '/factoryProduceSaleAll/factoryProduceSaleAll/listTodo',
        remove2: '/factoryProduceSaleAll/factoryProduceSaleAll/deleteByIdOther/',
        submitProduct: '/factoryProduceMain/factoryProduceMain/submitProduct',
      },
      tableMaxHeight: window.innerHeight - 900,
    };
  },
  created() {
  },
  methods: {
    /** 查询请购单（自制/采购/外协）列表 */
    getList() {
      this.loading = true;
      getAction(this.url.list, this.queryParams).then(response => {
        this.columns = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    editGoods(row) {
      this.$refs.editGoodsForm.show(row);
    }, /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.handleQuery();
    },
    getList2() {
      this.loading2 = true;
      this.queryParams2.status = '0';
      this.queryParams2.type = '1';
      getAction(this.url.list2, this.queryParams2).then(response => {
        this.columns2 = response.rows;
        this.total2 = response.total;
        this.loading2 = false;
      });
    },
    handleAdd() {
      this.open = true;
      this.loading = false;
      this.columns = [];
      this.columns2 = [];
      this.getList();
      this.getList2();
      this.form = {};
      /*this.form.saleDate = null;
      this.form.planStartDate = null;
      this.form.planFinishDate = null;
      this.form.workshopName = null;*/
    },
    handleDelete(row) {
      const id = row.id;
      deleteAction(this.url.remove2, id).then(response => {
        this.$modal.msgSuccess("删除成功");
        this.getList2();
        this.handleQuery();
      }).catch(() => {
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.$emit('ok');
      // this.reset();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.dataList = selection;
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    submitProd() {
      if (this.columns2.length === 0) {
        this.$modal.msgError("请先选择产品再提交！");
        return;
      }
      if (this.form.saleDate != null && this.form.saleDate != '' && this.form.saleDate != 'undefined') {
        let goodsSaledoIds = [];
        for (let i = 0; i < this.columns2.length; i++) {
          goodsSaledoIds.push(this.columns2[i].id);
        }
        const params = {};
        params.goodsSaledoIds = goodsSaledoIds.toString();
        params.saleDate = this.form.saleDate;
        params.planStartDate = this.form.planStartDate;
        params.planFinishDate = this.form.planFinishDate;
        params.workshopName = this.form.workshopName;
        params.type = "1";
        getAction(this.url.submitProduct, params).then(response => {
          this.$modal.msgSuccess("提交成功!");
          this.open = false;
          this.handleQuery();
          this.$parent.getList()
        }).catch(() => {
        });
      } else {
        this.$modal.msgError("请填写需求日期！");
        return;
      }
    },
    /** 提交按钮 */
    submitTodo() {
      let that = this;
      const ids = this.ids;
      if (ids == null || ids == '' || ids == 'undefined') {
        that.$modal.msgError("请选择一条记录");
        return;
      }
      let arrays = that.dataList;
      for (let i = 0; i < arrays.length; i++) {
        if (arrays[i].counts === 0) {
          that.$modal.msgError("订单数量不能为0");
          //that.$modal.msgError(arrays[i].name + "订单数量不能为0");
          return;
        }
      }
      that.$refs["form"].validate(valid => {
        if (valid) {
          const goodsSaledo = Object.assign({});
          goodsSaledo.columnsOther = that.dataList;
          goodsSaledo.type="1";
          addAction(that.url.insertTodoOther, goodsSaledo).then(response => {
            that.$modal.msgSuccess("添加成功");
            // this.open = false;
            that.$emit('ok');
            that.getList2();
            that.handleQuery();
          });
        }
      });
    },
    getSummaries(param) {
      // console.log(param);
      const { columns, data } = param;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        // 只合计amount1和amount3，想合并哪些列就在这里指定
        if (column.property === "orderCount" || column.property === "goodsTotalPrice" || column.property === "goodsTaxTotalPrice") {

          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return accAdd(prev, curr);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },

  }
};
</script>
